<script setup>
// 引入 Vue 的 ref 函数用于创建响应式变量
import { ref,onMounted } from 'vue';
import { uploadModelFiles } from '@/api/modelApi'; // 引入新的模型 API
// 引入 Pinia 的 store
import { useModelStore } from '@/store/model';
import { storeToRefs } from 'pinia';
import { useSystemStore } from '@/store/system';
import { getModels } from '@/api/monitoringApi'; 
// 使用 Pinia store
const systemStore = useSystemStore();
const models = ref([]); // 用于存储模型配置

// 使用 store
const modelStore = useModelStore();
const { config } = storeToRefs(modelStore);

// 保存配置的函数
const saveConfig = () => {
  // 更新模型名称和阈值到状态
  modelStore.updateConfig({
    name: systemStore.selectedModel,
    confidence: config.value.confidence,
    iou: config.value.iou,
  });
  console.log('配置已保存',useModelStore().config); // 提示用户配置已保存
};

// 响应式变量，用于存储上传的文件列表
const files = ref([]);

// 最大文件数量限制
const maxFiles = 5;

// 允许的文件格式
const allowedFormats = new Set(['onnx', 'pt']);

// 处理文件选择的函数
const handleFileChange = async (event) => {
  // 获取选择的文件
  const selectedFiles = [...event.target.files];
  // 过滤出符合格式的文件
  const validFiles = selectedFiles.filter((file) => {
    const fileExtension = file.name.split('.').pop().toLowerCase();
    return allowedFormats.has(fileExtension);
  });

  // 检查文件数量是否超过限制
  if (validFiles.length + files.value.length > maxFiles) {
    notify(`最多只能上传 ${maxFiles} 个文件`);
    return;
  }

  // 更新文件列表
  files.value = [...files.value, ...validFiles];
};

// 上传文件并更新状态管理
const uploadFiles = async () => {
  const formData = new FormData();
  files.value.forEach((file) => {
    formData.append('files', file);
  });
  formData.append('confidence_threshold', config.value.confidence);
  formData.append('iou_threshold', config.value.iou);

  try {
    const response = await uploadModelFiles(formData); // 调用新的 API
    console.log('上传响应:', response);
    
    if (response.length === 0) {
      notify(response.message);
    } else {
      console.log('文件上传成功');
      // 更新下拉列表的数据
      const modelsResponse = await getModels(); // 重新获取模型配置
      models.value = modelsResponse; // 更新模型列表
      console.log('更新后的模型数据:', models.value); // 打印更新后的模型数据
      clearFiles();
    }
  } catch (error) {
    console.log('文件上传失败，请重试');
  }
};

// 移除单个文件的函数
const removeFile = (index, event) => {
  event.stopPropagation(); // 阻止事件冒泡
  files.value.splice(index, 1);
};

// 清空所有文件的函数
const clearFiles = () => {
  files.value = [];
};

// 处理拖动上传的函数
const handleDrop = (event) => {
  event.preventDefault();
  const dt = event.dataTransfer;
  const selectedFiles = [...dt.files];
  handleFileChange({ target: { files: selectedFiles } });
};

// 处理拖动经过的函数
const handleDragOver = (event) => {
  event.preventDefault();
};

// 引用文件输入框，用于触发文件选择
const fileInput = ref(null);
const triggerFileInput = () => {
  fileInput.value.click();
};

const showUploadModal = ref(false); // 控制弹窗显示的变量

// 确认上传文件的函数
const confirmUpload = async () => {
  await uploadFiles(); // 调用上传文件的函数
  showUploadModal.value = false; // 关闭弹窗
};

// 取消上传文件的函数
const cancelUpload = () => {
  clearFiles(); // 清空文件列表
  showUploadModal.value = false; // 关闭弹窗
};

onMounted(async () => {
  try {
    const response = await getModels(); // 获取模型配置
    console.log('获取模型成功:', response);
    if (response.length !== 0) {
      models.value = response; // 存储模型配置
      console.log('models:', models.value); // 打印模型数据以调试
    } else {
      console.error(response.message);
    }
  } catch (error) {
    console.error('获取模型失败:', error);
  }
  systemStore.fetchStatistics();
});
</script>

<template>
  <div class="mx-auto max-w-full p-4">
    <h1 class="mb-6 text-2xl font-bold text-gray-800">模型配置</h1>
    <!-- 其他配置表单 -->
    <div class="rounded-lg bg-white p-4 shadow-md">
        <!-- 添加模型选择部分 -->
    <div class="mb-6">
      <label class="block mb-2 text-lg font-semibold text-gray-800">请选择模型</label>
      <select
            v-model="systemStore.selectedModel"
            class="block w-full rounded-md border border-gray-300 bg-white text-lg text-gray-700 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
          >
            <option
              v-for="model in models"
              :key="model.id"
              :value="model.file_path"
            >
            {{ model.file_path }} 
              <!-- {{ model.file_path }} - 置信度: {{ model.confidence_threshold }} - IOU: {{ model.iou_threshold }} -->
            </option>
          </select>
    </div>

      <div class="grid grid-cols-2 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-800">
            置信度阈值
          </label>
          <input
            v-model="config.confidence"
            type="number"
            step="0.01"
            class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
          />
          <input
            v-model="config.confidence"
            type="range"
            min="0"
            max="1"
            step="0.01"
            class="mt-1 block w-full border border-gray-300"
          />
          <span class="text-sm text-gray-500">{{ config.confidence }}</span>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-800">IOU阈值</label>
          <input
            v-model="config.iou"
            type="number"
            step="0.01"
            class="mt-1 block w-full rounded-md border border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
          />
          <input
            v-model="config.iou"
            type="range"
            min="0"
            max="1"
            step="0.01"
            class="mt-1 block w-full border border-gray-300"
          />
          <span class="text-sm text-gray-500">{{ config.iou }}</span>
        </div>
      </div>

      <!-- 文件上传 -->
      <!-- <div class="mt-6">
        <label class="block text-sm font-medium text-gray-800">上传文件</label>
        <div
          @drop="handleDrop"
          @dragover="handleDragOver"
          @click="triggerFileInput"
          class="mt-1 flex h-32 w-full cursor-pointer items-center justify-center rounded-md border-2 border-dashed border-gray-300 hover:border-blue-500"
        >
          <span class="text-gray-500">拖动文件到此处或点击选择文件</span>
          <input
            ref="fileInput"
            type="file"
            multiple
            @change="handleFileChange"
            class="pointer-events-none absolute h-full w-full opacity-0"
            accept=".pt,.onnx"
          />
        </div>
        <p class="mt-2 text-sm text-gray-500">支持的格式: .pt, .onnx</p>
        <ul class="mt-2">
          <li
            v-for="(file, index) in files"
            :key="index"
            class="flex items-center justify-between"
          >
            <span>{{ file.name }}</span>
            <button
              @click="(event) => removeFile(index, event)"
              class="text-red-500 hover:underline"
            >
              移除
            </button>
          </li>
        </ul>
        <button
          v-if="files.length > 0"
          @click="clearFiles"
          class="mt-2 text-red-500 hover:underline"
        >
          清空所有文件
        </button>
      </div> -->
    <button @click="saveConfig" class="mr-2 rounded bg-green-500 px-4 py-2 font-bold text-white hover:bg-green-700">保存配置</button>
      <button
        @click="showUploadModal = true"
        class="mt-4 rounded bg-blue-500 px-4 py-2 font-bold text-white hover:bg-blue-700"
      >
        上传文件
      </button>
    </div>

    <!-- 上传文件弹窗 -->
    <div v-if="showUploadModal" class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50">
      <div class="bg-white p-10 w-2/4 rounded-lg shadow-lg">
        <h2 class="text-lg font-bold mb-4">上传文件</h2>
        <div
          @drop="handleDrop"
          @dragover="handleDragOver"
          @click="triggerFileInput"
          class="h-64 w-full cursor-pointer border-2 border-dashed border-gray-300 flex items-center justify-center"
        >
          <span class="text-gray-500">拖动文件到此处或点击选择文件</span>
          <input
            ref="fileInput"
            type="file"
            multiple
            @change="handleFileChange"
            class="pointer-events-none absolute h-full w-full opacity-0"
            accept=".pt,.onnx"
          />
        </div>
        <p class="mt-2 text-sm text-gray-500">支持的格式: .pt, .onnx</p>
        <ul class="mt-2">
          <li
            v-for="(file, index) in files"
            :key="index"
            class="flex items-center justify-between"
          >
            <span>{{ file.name }}</span>
            <button
              @click="(event) => removeFile(index, event)"
              class="text-red-500 hover:underline"
            >
              移除
            </button>
          </li>
        </ul>
        <button
          v-if="files.length > 0"
          @click="clearFiles"
          class="mt-2 text-red-500 hover:underline"
        >
          清空所有文件
        </button>
        <div class="mt-4 flex justify-end">
      
          <button @click="cancelUpload" class="mr-2 text-gray-500">取消</button>
          <button @click="confirmUpload" class="rounded bg-blue-500 px-4 py-2 font-bold text-white hover:bg-blue-700">确认上传</button>
        </div>
      </div>
    </div>
  </div>
</template>
